/*
 * Copyright (c) SiteWhere, LLC. All rights reserved. http://www.sitewhere.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */
package com.smartthing.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.smartthing.spi.SmartThingException;
import com.smartthing.spi.SmartThingSystemException;
import com.smartthing.spi.error.ErrorCode;
import com.smartthing.spi.error.ErrorLevel;
import com.smartthing.spi.user.IUser;

/**
 * Provides helper methods for dealing with currently logged in user.
 * 
 * @author Derek
 */
public class LoginManager {

    /**
     * Get the currently logged in user from Spring Security.
     * 
     * @return
     * @throws SmartThingException
     */
    public static IUser getCurrentlyLoggedInUser() throws SmartThingException {
	Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	if (auth == null) {
	    throw new SmartThingSystemException(ErrorCode.NotLoggedIn, ErrorLevel.ERROR, 401);
	}
	if (!(auth instanceof SitewhereAuthentication)) {
	    throw new SmartThingException("Authentication was not of expected type: "
		    + SitewhereAuthentication.class.getName() + " found " + auth.getClass().getName() + " instead.");
	}
	return (IUser) ((SitewhereAuthentication) auth).getPrincipal();
    }
}